package com.backstage.controller;

import com.backstage.pojo.Admin;
import com.backstage.service.AdminService;
import com.backstage.utils.CommonDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
@RequestMapping("/admin")
public class LoginController {
//    @Autowired
//    private UserService userService;

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "admin/login";
    }


    /**
     * 用户登录
     *
     * @param name
     * @param password
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST)
    public String login(String name, String password, HttpSession session, HttpServletRequest request, Model model) {

        Admin admin = adminService.selectUserName(name);
        if (admin == null) {
            model.addAttribute("errMsg", "用户不存在");
            return "admin/login";
        }

        String passwordDB = admin.getPassword();
        if (!passwordDB.equals(password)) {
            model.addAttribute("errMsg", "密码错误");
            return "admin/login";
        }

        session.setAttribute("user_name", admin.getName());
        session.setAttribute("login_status",Boolean.TRUE);
        admin.setUpdatetime(CommonDate.newData());
        adminService.updateLoginTime(admin);
        //model.addAttribute("errMsg","登录成功");
        return "redirect:/admin/index";
    }


    /**
     * 用户退出
     *
     * @param session
     * @param attributes
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session, RedirectAttributes attributes) {
        session.removeAttribute("user_name");
        session.removeAttribute("login_status");
        attributes.addFlashAttribute("message", "用户退出成功");
        return "admin/login";
    }
}
